<template>
  <div>
    <!-- 搜索区域 -->
    <el-row>
      <el-form :inline="true" :model="queryInfo">
        <el-form-item label="标题名称">
          <el-input v-model="queryInfo.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="FM类型">
          <el-select
            v-model="queryInfo.fmCategoryId"
            clearable
            @clear="getType()"
            placeholder="请选择类型"
            style="width:200px;"
          >
            <el-option
              v-for="item in options"
              :label="item.category_name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getdata">搜索</el-button>
          <el-button type="primary" @click="showAddcommd">新增FM</el-button>
          <el-button type="danger" @click="delBacth">批量删除</el-button>
          <!-- 新增或修改弹出框 -->
          <el-dialog
            v-model="dialogVisible"
            :title="title"
            width="600"
            :before-close="cancel"
            ref:ruleFormRef
          >
            <el-form
              :model="dataList"
              label-width="auto"
              style="max-width: 600px"
              ref="ruleFormRef"
              :rules="rules"
            >
              <el-form-item label="名称">
                <el-input
                  v-model="dataList.title"
                  placeholder="请输入名称"
                  style="width: 500px;"
                />
              </el-form-item>
              

              <el-form-item label="封面图">
                <el-upload
                  drag
                  class="avatar-uploader"
                  method="post"
                  action="http://localhost:8081/sfzy/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="form.imgUrl" :src="`${form.imgUrl}`" class="avatar" />
                  <div v-else>
                    <el-icon class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </div>
                </el-upload>
              </el-form-item>
              <el-form-item label="类型">
                <el-col :span="24">
                  <el-form-item>
                    <el-select
                      v-model="dataList.fmCategoryId"
                      placeholder="请选择类型"
                      style="width:468px;"
                      clearable
                      @clear="getType()"
                    >
                      <el-option
                        v-for="item in options"
                        :label="item.category_name"
                        :value="item.id"
                        :key="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-form-item>
              <el-form-item id="button">
                <el-button type="primary" @click="add" v-if="dataList.addOrUpdateFlag<3">确认</el-button>
                <el-button type="primary" @click="cancel" v-if="dataList.addOrUpdateFlag<3">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 表格区域 -->
    <el-table
      :data="dataList1"
      border
      style="width: 100%"
      stripe="true"
      :row-style="{height: '50px'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" prop="id" label="ID"></el-table-column>
      <el-table-column align="center" prop="title" label="标题"></el-table-column>  
      <el-table-column align="center" prop="fmCategory.categoryName" label="所属类型"></el-table-column>
      <el-table-column prop="listImage" label="封面图" width="130">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px; text-align: center"
            :src="'http://localhost:8081/sfzy' + scope.row.listImage"
            fit="contain"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template v-slot="scope">
         
          <el-button type="primary" plain @click="showUpdatecommd(scope.row)">编辑</el-button>
          <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
          
        </template>
      </el-table-column>
    </el-table>
    <div id="footer">
      <el-pagination
        background
        :default-page-size="5"
        :page-sizes="[5, 8, 10]"
        :size="size"
        :disabled="disabled"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="changePageNum"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>
    
<script setup >
import { ref, onMounted, getCurrentInstance, watchEffect,onBeforeUnmount } from "vue";
import {
  ElMessageBox,
  ElMessage
} from "element-plus";

import { SortUp, Plus } from "@element-plus/icons-vue";
import ArticleCategory from "./ArticleCategory.vue";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";

const dialogVisible = ref(false);
const ruleFormRef = ref();
const dialogRef = ref(null); // 对话框的ref
const currentInstance = getCurrentInstance();
const { $http } = currentInstance.appContext.config.globalProperties;
const daterange = ref("");
const dataList1 = ref([]);
const typeList = ref([]);
// 定义响应式数据content，初始为空字符串
const content = ref("");

const quillEditorRef = ref(null);

const total = ref();
const title = ref("");
const address = ref("");
let options = ref([]);
let ids = ref([]);

// 定义查询对象 用来获取表单数据
let queryInfo = ref({
  title: "",
  fmCategoryId: "",
  pageNum: 1,
  pageSize: 5
});
// 定义新增或修改信息对象
const dataList = ref({
  addOrUpdateFlag: 1, // 判断是新增还是修改的标志 1:新增 2：修改
  id: 0, // id
  title: "", // 名称
  listImage: "", // 缩略图地址
  fmCategoryId: "", // 分类id
  del: 0 //逻辑删除状态
});

/*----------------封面图部分------------------------*/
let form = ref({
  imgUrl: ""
});
const imageUrl = ref(""); // 图片上传成功的钩子
const handleAvatarSuccess = (response, uploadFile) => {
  // 保存相对路径到相关数据对象，以便传给后端
  const relativeImagePath = response.data; // 拼接完整的图片路径在弹出框中显示
  const fullImagePath = `http://localhost:8081/sfzy${response.data}`;
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  form.value.imgUrl = fullImagePath; //传回数据库的路径
  dataList.value.listImage = relativeImagePath;
};
onBeforeUnmount(() => {
  URL.revokeObjectURL(imageUrl.value);
});
//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload = rawFile => {
  const allowedFormats = ["image/jpeg", "image/png"]; // 允许的文件格式
  if (!allowedFormats.includes(rawFile.type)) {
    this.$message.error("文件格式必须是 JPG 或 PNG！");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
/*----------------添加或修改数据------------------------*/
//添加或修改数据
function add() {
  if (dataList.value.addOrUpdateFlag == 1) {
    console.log(dataList.value);
    $http({
      method: "post",
      url: "http://localhost:8081/sfzy/fm",
      data: dataList.value
    }).then(res => {
      console.log("res=" + res);
      if (res.data.code == 200) {
        ElMessage.success("添加成功！");
        res.data.message;
      } else {
        ElMessage.error("添加失败！");
      }
      //再次查询
      getdata();
      //调用取消清空数据
      cancel();
    });
  } else if (dataList.value.addOrUpdateFlag == 2) {
    $http({
      method: "put",
      url: "http://localhost:8081/sfzy/fm",
      data: dataList.value
    }).then(res => {
      console.log("res=" + res);
      if (res.data.code == 200) {
        ElMessage.success("修改成功！");
        res.data.message;
      } else {
        ElMessage.error("修改失败！");
      }
      //再次查询
      getdata();
      //调用取消清空数据
      cancel();
    });
  }
}

//挂载后执行请求community数据
onMounted(() => {
  getdata();
  getType();
});
//数据请求方法
function getdata() {
  $http({
    method: "get",
    url: "http://localhost:8081/sfzy/fm/page",
    params: queryInfo.value
  }).then(res => {
    dataList1.value = res.data.data.list;
    total.value = res.data.data.total;
  });
}

//获取所有文章分类名
function getType() {
  $http({
    method: "get",
    url: "http://localhost:8081/sfzy/fmCategoryMap",
  }).then(res => {
    console.log(res.data.data);
    options.value = res.data.data;
    }); 
}

//获取selection中的数据
function handleSelectionChange(val) {
  ids.value = val.map(item => item.id);
}

//pageNum
function changePageNum(num) {
  // 修改页码
  queryInfo.value.pageNum = num;
  //再次查询
  getdata();
}

//pageSize
function handleSizeChange(size) {
  queryInfo.value.pageSize = size;
  getdata();
}

//新增
function showAddcommd() {
  title.value = "新增";
  dialogVisible.value = true;
  dataList.value.addOrUpdateFlag = 1;
}

//修改文章
function showUpdatecommd(val) {
  console.log(val);
  title.value = "修改";
  dialogVisible.value = true;
  dataList.value.addOrUpdateFlag = 2;
  
  // 回显
  Object.assign(dataList.value, {
    id: val.id,
    title: val.title,
    listImage: val.listImage,
    fmCategoryId: val.fmCategoryId, // 确保 categoryId 设置正确
    del: val.del
  });
  
  form.value.imgUrl = `http://localhost:8081/sfzy${val.listImage}`;
}

//取消
function cancel() {
  dialogVisible.value = false;
  address.value = [];
  form.value.imgUrl = "";
  Object.assign(dataList.value, {
    addOrUpdateFlag: 1,
    id: 0,
    title: "",
    listImage: "",
    del: 0
  });
  //再次查询
  getdata();
}

/*---------------- 删除/批量删除 部分------------------------*/
//删除
function del(id) {
  ElMessageBox.confirm("确认要删除数据吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      $http({
        method: "delete",
        url: "http://localhost:8081/sfzy/fm/" + id
      }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功！");
          getdata();
        } else {
          ElMessage.error("删除失败！");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除！"
      });
    });
}
//批量删除
function delBacth() {
  if (ids.value != null && ids.value != "") {
    ElMessageBox.confirm("确认要删除数据吗?", "Warning", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        $http({
          method: "delete",
          url: "http://localhost:8081/sfzy/fm?ids=" + ids.value
        }).then(res => {
          if (res.data.code == 200) {
            ElMessage.success("删除成功！");
            getdata();
          } else {
            ElMessage.error("删除失败！");
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！"
        });
      });
  }
}
</script>
    
<style scoped>
:deep(.ql-container) {
  min-height: 200px;
  min-width: 468px;
  max-width: 468px;
  max-height: 200px;
}

#button {
  margin-left: 250px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-pagination {
  margin-left: 200px;
}

#footer {
  height: 80px;
  margin: 40px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar{
  width: 150px;
  height: 150px;
}
</style>